<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-form-item label="开始时间 :" prop="startTime">
      <span v-if="formType === 'detail'">{{ formatDate(formData.startTime) }}</span>

        <el-date-picker
          v-model="formData.startTime"
          type="date"
          value-format="x"
          placeholder="选择开始时间"
          v-if="formType !== 'detail'"
        />
      </el-form-item>
      <el-form-item label="结束时间 :" prop="endTime">
        <span v-if="formType === 'detail'">{{ formatDate(formData.endTime) }}</span>

        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结束时间"
          v-if="formType !== 'detail'"
        />
      </el-form-item>
     
      <el-form-item label="活动名称 :" prop="activityName">
        <span v-if="formType === 'detail'">{{ formData.activityName }}</span>
        <el-input v-model="formData.activityName" placeholder="请输入活动名称" v-if="formType !== 'detail'"/>
      </el-form-item>
      
      <el-form-item label="活动人数 :" prop="maxNumber">
        <span v-if="formType === 'detail'">{{ formatMaxNumber(formData.maxNumber) }} </span>
        <el-input v-model="formData.maxNumber" placeholder="请输入人数" v-if="formType !== 'detail'"/>
      </el-form-item>
      <el-form-item label="已参加人数 :" prop="participantsNumber" v-if="formType === 'detail'">
        <span v-if="formType === 'detail'">{{ formatParticipantsNumber(formData.participantsNumber) }}</span>
      </el-form-item>
      <el-form-item label="活动状态 :" prop="activityState">
        <dict-tag
          v-if="formType === 'detail'"
          :type="DICT_TYPE.ACTIVITY_STATE"
          :value="formData.activityState ?? ''"
        />
        <el-select v-model="formData.activityState" placeholder="请选择活动状态：开始，暂停，结束" v-if="formType !== 'detail'">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ACTIVITY_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            
          />
        </el-select>
      </el-form-item>
      <!-- 渲染 HTML 内容 -->
      <!-- <el-form-item label="评选规则 :" prop="rules">
        <span v-if="formType === 'detail'">
          
          <span v-html="formData.rules"></span>
        </span>
        <Editor  v-else v-model="formData.rules" height="150px" />
      </el-form-item> -->

      <el-form-item label="参与要求 :" prop="participationRules">
        <span v-if="formType === 'detail'">
          <!-- 渲染 HTML 内容 -->
          <span v-html="formData.participationRules"></span>
        </span>
        <Editor  v-else v-model="formData.participationRules" height="150px" />
      </el-form-item>
      <!-- 渲染 HTML 内容 -->
      <!-- <el-form-item label="奖励方法 :" prop="rewardRules">
        <span v-if="formType === 'detail'">
          
          <span v-html="formData.rewardRules"></span>
        </span>
        <Editor  v-else v-model="formData.rewardRules" height="150px" />
      </el-form-item> -->
      
      <el-form-item label="介绍 :" prop="description">
        <!-- 如果是查看详情模式 -->
        <span v-if="formType === 'detail'">
          <!-- 渲染 HTML 内容 -->
          <span v-html="formData.description"></span>
        </span>
        <!-- 如果是编辑/新增模式 -->
        <Editor v-else v-model="formData.description" height="150px" />
        <!-- <Editor v-model="formData.description" height="150px" /> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="formType !== 'detail'">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { ActivityApi, ActivityVO } from '@/api/td/activity'
// import { formatDate } from '@/utils/formatTime' // 导入格式化时间的函数
/** 活动 表单 */
defineOptions({ name: 'ActivityForm' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
// const isDetail = ref(false) // 是否为详情模式
const formData = ref({
  id: undefined,
  endTime: undefined,
  startTime: undefined,
  activityName: undefined,
  maxNumber: undefined,
  rules: undefined,
  participationRules: undefined,
  rewardRules: undefined,
  activityState: undefined,
  description: undefined,
  participantsNumber: undefined,
})
const formRules = reactive({
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  activityName: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
  activityState: [{ required: true, message: '活动状态：开始，暂停，结束不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ActivityApi.getActivity(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ActivityVO
    if (formType.value === 'create') {
      await ActivityApi.createActivity(data)
      message.success(t('common.createSuccess'))
    } else {
      await ActivityApi.updateActivity(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    endTime: undefined,
    startTime: undefined,
    activityName: undefined,
    maxNumber: undefined,
    rules: undefined,
    participationRules: undefined,
    rewardRules: undefined,
    activityState: undefined,
    description: undefined,
    participantsNumber: undefined,
  }
  formRef.value?.resetFields()
}
/** 格式化日期 */
const formatDate = (timestamp: number | undefined): string => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()} 年 ${String(date.getMonth() + 1).padStart(2, '0')} 月 ${String(date.getDate()).padStart(2, '0')} 日`
}
// /** 格式化日期 */
// const formatDate = (timestamp: number | undefined): string => {
//   if (!timestamp) return ''
//   return new Date(timestamp).toLocaleDateString()
// }

/** 格式化人数 */
const formatMaxNumber = (maxNumber: number | undefined): string => {
  return maxNumber === 0 ? '无限制' : maxNumber?.toString()+ ' 人' || ''
}
const formatParticipantsNumber = (participantsNumber: number | undefined): string => {
  return participantsNumber === null ? '无' : participantsNumber?.toString()+'人' || '' 
}
// /** 获取活动状态标签 */
// const getActivityStateLabel = (state: number | undefined): string => {
//   const dict = getIntDictOptions(DICT_TYPE.ACTIVITY_STATE).find(
//     (item) => item.value === state
//   )
//   return dict?.label || ''
// }
</script>